package com.will.client.listener;

import com.will.client.NettyClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author 杨明智
 * @version:1.0
 * @create 2019年01月13日 12:24 PM
 * @description 重连监听
 **/
@ChannelHandler.Sharable
public class ConnectionListener implements ChannelFutureListener {

    private Logger logger = LoggerFactory.getLogger(ConnectionListener.class);

    private NettyClient client;

    public ConnectionListener(NettyClient client) {
        this.client = client;
    }
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (!channelFuture.isSuccess()) {
            logger.info("连接发生异常，重新连接中...");
            final EventLoop loop = channelFuture.channel().eventLoop();
            loop.schedule(new Runnable() {
                @Override
                public void run() {
                    client.createBootstrap(new Bootstrap(), loop);
                }
            }, 2L, TimeUnit.SECONDS);
        }else {
            logger.info("连接服务器成功...");
        }
    }
}
